package com.example.myapplication.net

import android.util.Log
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

abstract class AbstractCallback<T>(private val tag:String) : Callback<T> {

    abstract fun onSuccess(t : T)

    fun onError(call: Call<T>?, t: Throwable?){

    }

    override fun onResponse(call: Call<T>?, response: Response<T>?) {
        try{
            response ?: throw Throwable("onResponse Error because response is null")
            if (!response.isSuccessful) throw Throwable("onResponse Error because response is not success")
            val body = response.body()
            body ?: throw Throwable("onResponse Error because body is null")
            onSuccess(body)
        }catch (e : Throwable) {
            onFailure(call , e)
        }
    }

    override fun onFailure(call: Call<T>?, t: Throwable?) {
        Log.e("MainActivity","$tag > ${t?.localizedMessage}")
        onError(call , t)
    }
}